﻿using Microsoft.EntityFrameworkCore;
using Quartz;
using Quartz.Impl.Matchers;

namespace Application.Job
{
    /// <summary>
    /// 更新job的调度状态：taskJob.IsScheduled
    /// </summary>
    public class TaskStatusJob : IJob
    {
        private readonly JobManagerDbContext _dbContext;
        private readonly ISchedulerFactory _schedulerFactory;
        public TaskStatusJob(JobManagerDbContext dbContext, ISchedulerFactory schedulerFactory)
        {
            _dbContext = dbContext;
            _schedulerFactory = schedulerFactory;
        }

        public async Task Execute(IJobExecutionContext context)
        {
            try
            {
                var thisServerJobs = await _dbContext.JobTask.Where(s => s.ServerId == GlobalData.ServerId && s.IsEnable).ToListAsync();
                var serverIds = await _dbContext.KeyValue.Where(s => s.Type == KeyValueType.Server).Select(s => s.Id).ToListAsync();
                var isSingleService = serverIds.Count == 1 && serverIds[0] == GlobalData.ServerId;
                if (!isSingleService)
                {
                    var _scheduler = await _schedulerFactory.GetScheduler();
                    var scheduledJobs = await _scheduler.GetJobKeys(GroupMatcher<JobKey>.GroupEquals(JobGroupName.Task));

                    thisServerJobs.ForEach(s => s.IsScheduled = scheduledJobs.Any(a => a.Name == s.Id.ToString() && a.Group == JobGroupName.Task));
                    await _dbContext.SaveChangesAsync();
                }
            }
            catch (Exception ex)
            {
                await Console.Out.WriteLineAsync(ex.Message);
            }

        }
    }
}
